// 用于判断是呼叫者还是应答者
var isCaller = window.location.href.split("#")[1];

// 与信令服务器的WebSocket连接
var socket = new WebSocket("ws://127.0.0.1:3000");

// stun和turn服务器
var iceServer = {
  iceServers: [
    {
      url: "stun:stun.l.google.com:19302"
    },
    {
      url: "turn:numb.viagenie.ca",
      username: "webrtc@live.com",
      credential: "muazkh"
    }
  ]
};

// 创建PeerConnection实例 (参数为null则没有iceserver，即使没有stunserver和turnserver，仍可在局域网下通讯)
var pc = new webkitRTCPeerConnection(iceServer);
console.log("webkitRTCPeerConnection", pc);
// 获取本地音频和视频流
// 约束条件
const constraints = {
  audio: true,
  video: true
};

async function onSuccess(stream) {
  //绑定本地媒体流到video标签用于输出
  //document.getElementById('localVideo').src = URL.createObjectURL(stream);
  document.getElementById("local").srcObject = stream;
  //向PeerConnection中加入需要发送的流
  pc.addStream(stream);
  //如果是发起方则发送一个offer信令
  if (!isCaller) return;
  const offer = await pc.createOffer();
  console.log("offer", offer);
  pc.setLocalDescription(offer);
  const sendMsg = {
    type: "offer",
    caller: true,
    data: {
      sdp: offer
    }
  };
  socket.send(JSON.stringify(sendMsg));
}
function onError(err) {}

navigator.getUserMedia(constraints, onSuccess, onError);

// 发送ICE候选到其他客户端

let isSend = false;
pc.onicecandidate = function (event) {
  if (event.candidate !== null && !isSend) {
    //console.log("candidate", event);
    isSend = true;
    const sendMsg = {
      type: "icecandidate",
      data: {
        candidate: event.candidate
      }
    };
    socket.send(JSON.stringify(sendMsg));
  }
};

// 如果检测到媒体流连接到本地，将其绑定到一个video标签上输出
pc.onaddstream = function (event) {
  //console.log("remote-stream", event);
  document.getElementById("remote").srcObject = event.stream;
};

socket.onmessage = async function (event) {
  const socketMsg = JSON.parse(event.data);
  // console.log("socket-message", socketMsg);
  // 当应答者收到icecandidate时
  if (socketMsg.type === "icecandidate" && !isCaller) {
    pc.addIceCandidate(new RTCIceCandidate(socketMsg.data.candidate));
  }
  // 当呼叫者收到回应时
  if (socketMsg.type === "answer" && isCaller) {
    pc.setRemoteDescription(new RTCSessionDescription(socketMsg.data.sdp));
  }
  // 当应答者收到请求时
  if (socketMsg.type === "offer" && !isCaller) {
    pc.setRemoteDescription(new RTCSessionDescription(socketMsg.data.sdp));
    const answer = await pc.createAnswer();
    console.log("answer", answer);
    pc.setLocalDescription(answer);
    const sendMsg = {
      type: "answer",
      data: {
        sdp: answer
      }
    };
    socket.send(JSON.stringify(sendMsg));
  }
};
